package m.jclecai.com.activity;

import android.Manifest;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.squareup.okhttp.Request;
import com.tbruyelle.rxpermissions.RxPermissions;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.StringUtils;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.responseBody.BaseBody;
import m.jclecai.com.view.rounded.RoundedImageView;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import rx.functions.Action1;

public class UserInfoActivity extends BaseActivity {

    @BindView(R.id.iv_icon)
    RoundedImageView ivIcon;
    UserBean userBean;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_count)
    TextView tvCount;

    @Override
    public int getContentView() {
        return R.layout.activity_user_info;
    }

    @Override
    public void initView() {
        super.initView();
        setTitle("个人中心");
        leftOptionText("");
    }

    @Override
    protected void onResume() {
        super.onResume();
        showUserInfo();
    }

    void showUserInfo() {
        userBean = PreferenceUtil.readUser(this);
        if (userBean != null) {
            tvName.setText(userBean.getUsername());
            tvCount.setText(String.valueOf(userBean.getUser_goldcoin()));
            Glide.with(this)
                    .load(userBean.getUser_face())
                    .asBitmap()
                    .placeholder(R.drawable.my_head_de)
                    .error(R.drawable.my_head_de)
                    .into(ivIcon);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant_Result.CLEARALLUSERDATA) {
            setResult(resultCode);
            if (resultCode == RESULT_OK)
                finish();
        } else if (requestCode == Constant_Result.REQUESTIMAGE && resultCode == RESULT_OK) {
            /**
             * 处理本地图片
             */
            Log.d(TAG, "onActivityResult() called with: resultCode = [" + resultCode + "], data = [" + data + "]");
            // 获取返回的图片列表
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            showThumbImg(path.get(0));
            uploadIcon(StringUtils.encodeBase64File(path.get(0)));
        }
    }

    /**
     * 因为缩略图生成比较慢，所以延时200ms显示
     * 避免由于特殊情况 缩略图获取失败则使用imageloader加载
     *
     * @param url
     */
    void showThumbImg(final String url) {
        userBean.setUser_face(url);
        PreferenceUtil.writeUser(this, userBean);

        Glide.with(this)
                .load(url)
                .asBitmap()
                .placeholder(R.drawable.my_head_de)
                .error(R.drawable.my_head_de)
                .into(ivIcon);
    }

    @OnClick(R.id.ll_user)
    void openAlbum() {
        RxPermissions rxPermissions = new RxPermissions(this); // where this is an Activity instance
        rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        /**选择拍照**/
                        Intent intent = new Intent(UserInfoActivity.this, MultiImageSelectorActivity.class);
                        // 是否显示调用相机拍照
                        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, granted);
                        // 最大图片选择数量
                        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
                        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                        // intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
                        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                        startActivityForResult(intent, Constant_Result.REQUESTIMAGE);
                    }
                });
    }

    void uploadIcon(String base64) {
        showDialog();
        HashMap<String, String> pair = new HashMap<>();
        pair.put("userid", userBean.getUser_id());
        pair.put("file", base64);
        HttpManager.postAsyn(Constant_Url.USER_ICON, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay(getString(R.string.error_network));
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                BaseBody body = FastOk.get(response,BaseBody.class);
                if(body != null && body.getStatus() == 0){
                    DisPlay("上传成功");
                }else {
                    DisPlay("上传失败");
                }
            }
        }, pair);
    }
}
